package com.haochang.chunkvod.controller.adapter.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.fragment.order.ShopCartFragment;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.tools.vod.other.AppendImageUtil;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.activity.ActivityDialogEnum;
import com.haochang.chunkvod.view.vod.activity.ShopCartDialogActivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Paint;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/6/24 11:15
 *         本地购物车适配器
 */

public class CartExpandableAdapter extends BaseExpandableListAdapter
{
	private Context context;
	private ShopCartFragment shopCartFragment;
	private List<GoodsInfo> groupList = new ArrayList<GoodsInfo>();
	private List<List<FoodDetailInfo>> childList = new ArrayList<List<FoodDetailInfo>>();

	public CartExpandableAdapter(ShopCartFragment shopCartFragment, Context context, List<GoodsInfo> groupList)
	{
		this.context = context;
		this.shopCartFragment = shopCartFragment;
		this.groupList.clear();
		this.childList.clear();
		if (!CollectionUtils.isEmpty(groupList))
		{
			this.groupList.addAll(groupList);
			this.childList.addAll(getChildList());
		}
	}

	public void setData(List<GoodsInfo> groupList)
	{
		this.groupList.clear();
		this.childList.clear();
		if (!CollectionUtils.isEmpty(groupList))
		{
			this.groupList.addAll(groupList);
			this.childList.addAll(getChildList());
		}
		CartExpandableAdapter.this.notifyDataSetChanged();
	}

	public void updateData(GoodsInfo goodsInfo)
	{
		for (int i = 0; i < groupList.size(); i++)
		{
			GoodsInfo goodInfo = groupList.get(i);
			if (goodsInfo.getId() == goodInfo.getId() && goodsInfo.getGoodsId().equals(goodInfo.getGoodsId()) && goodsInfo.is_give() == goodInfo.is_give()
					&& goodsInfo.is_present() == goodInfo.is_present() && goodsInfo.getMenuId().equals(goodInfo.getMenuId()))
			{
				goodInfo.setStandard(goodsInfo.getStandard());
				goodInfo.setOrderNum(goodsInfo.getOrderNum());
				break;
			}
		}
		CartExpandableAdapter.this.notifyDataSetChanged();
	}

	@Override
	public int getGroupCount()
	{
		return groupList.size();
	}

	@Override
	public int getChildrenCount(int groupPosition)
	{
		return this.childList.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition)
	{
		return groupList.get(groupPosition);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition)
	{
		return childList.get(groupPosition).get(childPosition);
	}

	@Override
	public long getGroupId(int groupPosition)
	{
		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition)
	{
		return childPosition;
	}

	@Override
	public boolean hasStableIds()
	{
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition)
	{
		return false;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
	{
		GroupViewHolder groupViewHolder = null;
		if (null == convertView)
		{
			convertView = LayoutInflater.from(context).inflate(R.layout.item_shop_cart_first_layout, parent, false);
			groupViewHolder = new GroupViewHolder();
			groupViewHolder.tv_foodName = (BaseTextView) convertView.findViewById(R.id.tv_foodName);
			groupViewHolder.tv_num = (BaseTextView) convertView.findViewById(R.id.tv_num);
			groupViewHolder.tv_unit = (BaseTextView) convertView.findViewById(R.id.tv_unit);
			groupViewHolder.tv_totalPrice = (BaseTextView) convertView.findViewById(R.id.tv_totalPrice);
			groupViewHolder.img_del = (ImageView) convertView.findViewById(R.id.img_del);
			groupViewHolder.iv_direction = (ImageView) convertView.findViewById(R.id.iv_direction);
			groupViewHolder.tv_flavor_info = (BaseTextView) convertView.findViewById(R.id.tv_flavor_info);
			convertView.setTag(groupViewHolder);
		} else
			groupViewHolder = (GroupViewHolder) convertView.getTag();
		final GoodsInfo goodsInfo = this.groupList.get(groupPosition);
		groupViewHolder.tv_foodName.setText(goodsInfo.getGoodsName());

		if (!TextUtils.isEmpty(goodsInfo.getTaste_types()) || !TextUtils.isEmpty(goodsInfo.getStandard_types()))
		{
			groupViewHolder.tv_flavor_info.setVisibility(View.VISIBLE);
			if (!TextUtils.isEmpty(goodsInfo.getTaste_types()) && TextUtils.isEmpty(goodsInfo.getStandard_types()))
				parseFlavor(groupViewHolder.tv_flavor_info, goodsInfo.getFlavor());
			else if (TextUtils.isEmpty(goodsInfo.getTaste_types()) && !TextUtils.isEmpty(goodsInfo.getStandard_types()))
				parseStandard(groupViewHolder.tv_flavor_info, goodsInfo.getStandard());
			else if (!TextUtils.isEmpty(goodsInfo.getTaste_types()) && !TextUtils.isEmpty(goodsInfo.getStandard_types()))
				parseFlavor(groupViewHolder.tv_flavor_info, goodsInfo.getFlavor());
		} else
			groupViewHolder.tv_flavor_info.setVisibility(View.GONE);

		if (goodsInfo.is_give() || goodsInfo.is_present())
		{
			groupViewHolder.tv_totalPrice.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.doller_red), null, null, null);
			groupViewHolder.tv_totalPrice
					.setText(Html.fromHtml("<font color=#f04e39>" + SaleUtils.getSaleString(goodsInfo.getPrice() * goodsInfo.getOrderNum()) + "</font>"));
			groupViewHolder.tv_totalPrice.getPaint().setAntiAlias(true);//抗锯齿
			groupViewHolder.tv_totalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
			groupViewHolder.tv_foodName.append(AppendImageUtil.addImageSpan(context, R.drawable.btn, 10));
		} else
		{
			groupViewHolder.tv_totalPrice.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.doller_gray), null, null, null);
			groupViewHolder.tv_totalPrice.setText(SaleUtils.getSaleString(goodsInfo.getPrice() * goodsInfo.getOrderNum()));
		}
		//活动类型不显示数量选择框和单位
		if (goodsInfo.getGoods_type() == VodConstant.ACTIVE_TYPE)
		{
			groupViewHolder.tv_num.setVisibility(View.GONE);
			groupViewHolder.tv_unit.setVisibility(View.GONE);
		} else
		{
			groupViewHolder.tv_unit.setVisibility(View.VISIBLE);
			if (goodsInfo.getSurplus() <= 0)
			{
				groupViewHolder.tv_num.setVisibility(View.GONE);
				groupViewHolder.tv_unit.setText("估清");
			} else if (goodsInfo.getSurplus() > 0)
			{
				if (goodsInfo.getOrderNum() > goodsInfo.getSurplus())
				{
					ColorStateList redColors = ColorStateList.valueOf(0xfff04e39);
					String value = "仅剩" + goodsInfo.getSurplus() + goodsInfo.getUnit();
					SpannableStringBuilder spanBuilder = new SpannableStringBuilder(value);
					spanBuilder.setSpan(new TextAppearanceSpan(null, 0, DipPxConversion.sp2px(context, 12), redColors, null), 0, value.length(),
							Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
					groupViewHolder.tv_foodName.append(spanBuilder);
				}
				groupViewHolder.tv_num.setText(String.valueOf(goodsInfo.getOrderNum()));
				groupViewHolder.tv_num.setVisibility(View.VISIBLE);
				groupViewHolder.tv_unit.setText(goodsInfo.getUnit());
			}
		}
		groupViewHolder.img_del.setTag(goodsInfo);
		groupViewHolder.img_del.setOnClickListener(onBaseClickListener);
		groupViewHolder.tv_num.setTag(goodsInfo);
		groupViewHolder.tv_num.setOnClickListener(onBaseClickListener);
		if (TextUtils.isEmpty(goodsInfo.getGoodsDetial()))
			groupViewHolder.iv_direction.setVisibility(View.GONE);
		else
			groupViewHolder.iv_direction.setVisibility(View.VISIBLE);
		if (isExpanded)
			groupViewHolder.iv_direction.setImageResource(R.drawable.up);
		else
			groupViewHolder.iv_direction.setImageResource(R.drawable.down);
		return convertView;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
	{
		ChildViewHolder childViewHolder = null;
		if (null == convertView)
		{
			convertView = LayoutInflater.from(context).inflate(R.layout.item_shop_cart_second_layout, parent, false);
			childViewHolder = new ChildViewHolder();
			childViewHolder.tv_foodName = (BaseTextView) convertView.findViewById(R.id.tv_foodName);
			childViewHolder.tv_num_unit = (BaseTextView) convertView.findViewById(R.id.tv_num_unit);
			childViewHolder.tv_flavor_info = (BaseTextView) convertView.findViewById(R.id.tv_flavor_info);
			convertView.setTag(childViewHolder);
		} else
			childViewHolder = (ChildViewHolder) convertView.getTag();
		FoodDetailInfo info = this.childList.get(groupPosition).get(childPosition);
		childViewHolder.tv_foodName.setText(info.getName());
		if (info.getNumber() == 0)
		{
			childViewHolder.tv_num_unit.setVisibility(View.INVISIBLE);
		} else
		{
			childViewHolder.tv_num_unit.setText(String.valueOf(info.getNumber() + info.getUnit()));
			childViewHolder.tv_num_unit.setVisibility(View.VISIBLE);
		}
		if (!TextUtils.isEmpty(info.getTaste_types()))
		{
			childViewHolder.tv_flavor_info.setVisibility(View.VISIBLE);
			parseFlavor(childViewHolder.tv_flavor_info, info.getFlavor());
		} else if (!TextUtils.isEmpty(info.getStandard_types()))
		{
			childViewHolder.tv_flavor_info.setVisibility(View.VISIBLE);
			parseStandard(childViewHolder.tv_flavor_info, info.getStandard());
		} else
			childViewHolder.tv_flavor_info.setVisibility(View.GONE);
		return convertView;
	}

	private OnBaseClickListener onBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			final GoodsInfo goodsInfo = (GoodsInfo) v.getTag();
			switch (v.getId())
			{
			case R.id.img_del:
				new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(false).contentName("确认要从购物车删除该商品吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								ShoppingCartManager.deleteGoods(goodsInfo);
								groupList.remove(goodsInfo);
								CartExpandableAdapter.this.notifyDataSetChanged();
								EventProxy.notifyEvent(IEventConstant.EVENT_SHOP_CART_PRICE, goodsInfo);
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			case R.id.tv_num:
				String flavor = goodsInfo.getTaste_types();
				String standard = goodsInfo.getStandard_types();
				ActivityDialogEnum activityDialogEnum = null;
				JSONArray array = null;
				try
				{
					if (!TextUtils.isEmpty(flavor) && TextUtils.isEmpty(standard))
					{
						activityDialogEnum = ActivityDialogEnum.FLAVOR;
						array = new JSONArray(flavor);
					} else if (TextUtils.isEmpty(flavor) && !TextUtils.isEmpty(standard))
					{
						activityDialogEnum = ActivityDialogEnum.SIZE;
						array = new JSONArray(standard);
					} else if (!TextUtils.isEmpty(flavor) && !TextUtils.isEmpty(standard))
					{
						activityDialogEnum = ActivityDialogEnum.FLAVOR;
						array = new JSONArray(flavor);
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
				if (array != null && array.length() > 0)
				{
					Intent intent = new Intent(context, ShopCartDialogActivity.class);
					intent.putExtra(IntentKey.GOODSINFO, goodsInfo);
					intent.putExtra(IntentKey.ACTIVITY_ENUM, activityDialogEnum);
					if (activityDialogEnum == ActivityDialogEnum.SIZE)
					{
						intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
						intent.putExtra(IntentKey.STANDARD, goodsInfo.getStandard());
					} else
						intent.putExtra(IntentKey.FLAVOR, goodsInfo.getFlavor());
					shopCartFragment.startActivityForResult(intent, IntentCode.SHOP_CART_REQUEST);
				} else
				{
					Intent intent = new Intent(context, ShopCartDialogActivity.class);
					intent.putExtra(IntentKey.GOODSINFO, goodsInfo);
					intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.DEFAULT);
					intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
					shopCartFragment.startActivityForResult(intent, IntentCode.SHOP_CART_REQUEST);
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 获取分组下FoodDetailInfo列表
	 * 如果是套餐详情或者活动详情里面有不同口味的商品，要对数据进行再次拆分
	 *
	 * @return FoodDetailInfo列表
	 */
	private List<List<FoodDetailInfo>> getChildList()
	{
		List<List<FoodDetailInfo>> childrenList = new ArrayList<List<FoodDetailInfo>>();
		try
		{
			for (int i = 0; i < groupList.size(); i++)
			{
				GoodsInfo goodInfo = groupList.get(i);
				List<FoodDetailInfo> list = new ArrayList<FoodDetailInfo>();
				if (!TextUtils.isEmpty(goodInfo.getGoodsDetial()))
				{
					JSONArray array = new JSONArray(goodInfo.getGoodsDetial());
					//解析详情数据,详情里面包含多个单品，每个单品包含不同的口味，需进行拆分
					if (array.length() > 0)
					{
						for (int j = 0; j < array.length(); j++)
						{
							JSONObject obj = array.optJSONObject(j);
							String combos = obj.optString("combos");
							if (TextUtils.isEmpty(combos))
							{
								// 活动或者套餐里面的单品
								parseDetailData(list, obj);
							} else
							{
								// 活动里面的套餐
								JSONArray jsonArray = new JSONArray(combos);
								if (jsonArray.length() > 0)
								{
									for (int k = 0; k < jsonArray.length(); k++)
									{
										JSONObject object = jsonArray.optJSONObject(k);
										parseDetailData(list, object);
									}
								}
							}
						}
					}
				}
				childrenList.add(list);
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		return childrenList;
	}

	/**
	 * 解析详情数据
	 * @param list 
	 * @param obj
	 */
	private void parseDetailData(List<FoodDetailInfo> list, JSONObject obj)
	{
		try
		{
			//活动或者套餐里面的单品
			String flavor_array = obj.optString("flavor_array");
			String standard = obj.optString("standard_type");
			if (!TextUtils.isEmpty(flavor_array))
			{
				//添加有口味的单品
				JSONArray jsonArray = new JSONArray(flavor_array);
				if (jsonArray.length() > 0)
				{
					for (int k = 0; k < jsonArray.length(); k++)
					{
						FoodDetailInfo info = new FoodDetailInfo();
						info.setName(obj.optString("name"));
						info.setUnit(obj.optString("unit"));
						info.setTaste_types(obj.optString("taste"));
						info.setNumber(jsonArray.optJSONObject(k).optInt("number"));
						info.setFlavor(jsonArray.optJSONObject(k).optString("flavor"));
						list.add(info);
					}
				}
			} else if (!TextUtils.isEmpty(standard) && ShoppingCartManager.isSelectStandard(standard))
			{
				//添加有规格的单品
				JSONArray jsonArray = new JSONArray(standard);
				if (jsonArray.length() > 0)
				{
					FoodDetailInfo info = new FoodDetailInfo();
					info.setName(obj.optString("name"));
					info.setUnit(obj.optString("unit"));
					info.setNumber(obj.optInt("number"));
					info.setStandard_types(standard);
					info.setStandard(ShoppingCartManager.getStandardDetail(standard));//二级详情商品里面设置默认配置的规格数据
					list.add(info);
				}
			} else
			{
				//添加无口味单品
				list.add(new FoodDetailInfo(obj, ""));
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 解析口味
	 *
	 * @param view_flavor 显示口味的tv
	 * @param value 口味值
	 */

	private void parseFlavor(BaseTextView view_flavor, String value)
	{
		if (!TextUtils.isEmpty(value))
		{
			try
			{
				JSONArray array = new JSONArray(value);
				if (array.length() > 0)
				{
					String flavorValue = "";
					for (int i = 0; i < array.length(); i++)
					{
						JSONObject jsonobject = array.getJSONObject(i);
						String name = jsonobject.optString("name");
						if (i == array.length() - 1)
							flavorValue += name;
						else
							flavorValue += name + "；";
					}
					view_flavor.setText(String.valueOf("口味：" + flavorValue));
				} else
				{
					view_flavor.setText("口味：标准");
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		} else
			view_flavor.setText("口味：标准");
	}

	/**
	 * 解析规格
	 *
	 * @param view_standard 显示规格的tv
	 * @param value 口味值
	 */

	private void parseStandard(BaseTextView view_standard, String value)
	{
		if (TextUtils.isEmpty(value))
			return;
		try
		{
			JSONArray array = new JSONArray(value);
			if (array.length() > 0)
			{
				String flavorValue = "";
				for (int i = 0; i < array.length(); i++)
				{
					JSONObject jsonobject = array.getJSONObject(i);
					String name = jsonobject.optString("name");
					if (i == array.length() - 1)
						flavorValue += name;
					else
						flavorValue += name + "；";
				}
				view_standard.setText(String.valueOf("规格：" + flavorValue));
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	protected class GroupViewHolder
	{
		protected BaseTextView tv_foodName;
		protected BaseTextView tv_num;
		protected BaseTextView tv_unit;
		protected BaseTextView tv_totalPrice;
		protected ImageView img_del;
		protected ImageView iv_direction;
		protected BaseTextView tv_flavor_info;
	}

	protected class ChildViewHolder
	{
		protected BaseTextView tv_foodName;
		protected BaseTextView tv_num_unit;
		protected BaseTextView tv_flavor_info;
	}

}
